package etcdx

import "C"
import (
	"context"
	"log"

	"github.com/gookit/color"
	clientv3 "go.etcd.io/etcd/client/v3"
)

const key = "nosql"
const value = "nosql"

type EtcdTest struct {
	client *clientv3.Client
}

func (c EtcdTest) Crud(ctx context.Context) {

	put, err := c.client.Put(ctx, key, value)
	c.client.Put(ctx, key, value+"_ok")
	if err != nil {
		panic(err)
	}
	color.Greenln(put.OpResponse(), "Header:", put.Header, "PrevKv:", put.PrevKv)

	get, err := c.client.Get(ctx, key)
	if err != nil {
		panic(err)
	}
	color.Yellowln(get.OpResponse(), "Header:", get.Header, get.More, "Kvs:", get.Kvs, get.Count)

	response, err := c.client.Delete(ctx, key)
	if err != nil {
		panic(err)
	}
	color.Blueln(response.OpResponse(), "Header:", response.Header, response.PrevKvs, response.Deleted)

}
func (c EtcdTest) TTl(ctx context.Context) error {
	// 创建租约
	// TTL is the advisory time-to-live in seconds. Expired lease will return -1.

	leaseResp, err := c.client.Grant(ctx, 5)
	if err != nil {
		return err
	}

	// 注册服务
	_, err = c.client.Put(ctx, key, value+"lease", clientv3.WithLease(leaseResp.ID))
	if err != nil {
		return err
	}

	// 自动续租
	keepAlive, err := c.client.KeepAlive(ctx, leaseResp.ID)
	if err != nil {
		return err
	}
	go c.keepAlive(ctx, keepAlive)
	// 监听租约状态_
	return nil
}
func (c EtcdTest) keepAlive(ctx context.Context, keepAlive <-chan *clientv3.LeaseKeepAliveResponse) {
	for {
		select {
		case <-ctx.Done():
			return
		case ka, ok := <-keepAlive:
			if !ok {
				log.Println("租约已失效")
				return
			}
			log.Printf("续租成功:%v TTL=%d", ka.ID, ka.TTL)
		}
	}
}

func (c EtcdTest) Closex() {
	c.client.Close()
}
